package cn.laixueit;

import cn.laixueit.client.BrandClient;
import cn.laixueit.client.SpecClient;
import cn.laixueit.client.SpuClient;
import cn.laixueit.pojo.Brand;
import cn.laixueit.pojo.Spu;
import cn.laixueit.pojo.search.Goods;
import cn.laixueit.repository.GoodsRepository;
import cn.laixueit.result.PageResult;
import cn.laixueit.service.SearchService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SearchApp.class)
public class Demo {

    @Autowired
    private ElasticsearchTemplate template;

    @Test
    public void t(){
        template.createIndex(Goods.class);
        template.putMapping(Goods.class);
    }

    @Autowired
    private GoodsRepository goodsRepository;

    @Test
    public void t2(){
        NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        searchQueryBuilder.withFilter(boolQuery);
        Page<Goods> goodsPage = goodsRepository.search(searchQueryBuilder.build());
        List<Goods> content = goodsPage.getContent();
        System.out.println("content = " + content);
    }

    @Autowired
    private BrandClient brandClient;
    @Test
    public void tf(){
        List<Brand> brandList = brandClient.brandListByCid(76l).getBody();
        System.out.println(brandList.size());
    }

    @Autowired
    private SearchService searchService;

    @Autowired
    private SpuClient spuClient;

    @Test
    public void build(){
        PageResult<Spu> result = spuClient.spuPage(null, true, 1, 50).getBody();
        long total = result.getTotal();
        int i =1;
        do{
            List<Spu> spuList = result.getItems();
            List<Goods> goodsList = spuList.stream().map(spu -> {
                try {
                    Goods goods = searchService.buildGoods(spu);
                    return goods;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }).collect(Collectors.toList());
            goodsRepository.saveAll(goodsList);
            total=total - 50;
            result = spuClient.spuPage(null, true, ++i, 50).getBody();
        }while (total>0);
    }

}
